<template>
  <CommonPage>
    <AppCrud
      ref="tableRef"
      :columns="columns"
      default-sort="createdAt"
      v-model:query="query"
      :get-data="processApi.page"
    >
      <query-item label="工序">
        <a-input
          allow-clear
          size="small"
          placeholder="请输入工序"
          v-model:value="query.name"
        ></a-input>
      </query-item>

      <template #action>
        <a-button type="primary" @click="onAdd">
          <template #icon><PlusOutlined></PlusOutlined></template>
          创建工序
        </a-button>
      </template>
    </AppCrud>

    <AppModal ref="modalRef" width="500px">
      <a-form ref="formRef" :model="formModel" :label-col="{ style: { width: '90px' } }">
        <a-form-item
          label="工序名称"
          name="name"
          :rules="[{ required: true, message: '此为必填项' }]"
        >
          <a-input placeholder="请输入工序名称" v-model:value="formModel.name"></a-input>
        </a-form-item>

        <a-form-item label="价格">
          <a-button size="small" type="link" @click="onCheckAll">全选</a-button>
          <a-button size="small" type="link" @click="onUnCheck">反选</a-button>
          <a-divider class="mt-5 mb-15"></a-divider>
          <div class="flex mb-10 align-center" v-for="price in prices">
            <a-checkbox v-model:checked="price.visible">
              <span>{{ getSize(price.sizeId).name }}</span>
            </a-checkbox>

            <a-input-number
              :disabled="!price.visible"
              :min="0"
              placeholder="请输入价格"
              v-model:value="price.price"
              size="small"
            >
              <template #addonAfter>元</template>
            </a-input-number>
          </div>
        </a-form-item>

        <a-form-item label="备注">
          <a-textarea
            placeholder="请输入备注信息"
            v-model:value="formModel.description"
          ></a-textarea>
        </a-form-item>
      </a-form>
    </AppModal>
  </CommonPage>
</template>
<script setup lang="ts">
import { AppCrud, AppModal, CommonPage, QueryItem } from '@/components/common'
import { useCrud } from '@/hooks/useCrud.ts'
import processApi, { PriceDto, ProcessTemplateDto } from '@/api/processTemplate.ts'
import sizeApi, { SizeDto } from '@/api/size.ts'
import { Button, Space, Tag } from 'ant-design-vue'

const tableRef = ref()

const query = ref({
  name: null,
})

const sizes = ref<SizeDto[]>([])

const prices = ref<PriceDto[]>([])

const columns = [
  {
    title: '工序名称',
    dataIndex: 'name',
    width: 180,
  },
  {
    title: '价格',
    dataIndex: 'weight',
    width: 400,
    render: ({ record }) => {
      return h(
        Space,
        record.prices.map((price) => {
          return h(Tag, {}, price.size.name + '：' + price.price + '元')
        }),
      )
    },
  },
  {
    title: '备注信息',
    dataIndex: 'description',
    width: 200,
  },
  {
    title: '创建时间',
    width: 150,
    dataIndex: 'createdAt',
  },
  {
    title: '操作',
    align: 'center',
    width: 140,
    render: ({ record }: any) => {
      return h(
        Space,
        {},
        {
          default: () => [
            h(
              Button,
              {
                size: 'small',
                type: 'primary',
                onClick: () => {
                  handleEdit(record)
                },
              },
              {
                default: () => '编辑',
              },
            ),
            h(
              Button,
              {
                size: 'small',
                danger: true,
                onClick: () => handleDelete(record.id),
              },
              {
                default: () => '删除',
              },
            ),
          ],
        },
      )
    },
  },
]

const { modalRef, formRef, formModel, handleEdit, handleAdd, handleDelete } =
  useCrud<ProcessTemplateDto>({
    name: '工序',
    initForm: {
      name: null,
      description: null,
      prices: [],
    },
    doCreate: (form) => {
      form.prices = prices.value
        .filter((p) => p.visible && p.price != null)
        .map((item) => {
          return {
            sizeId: item.sizeId,
            price: item.price,
          }
        })
      return processApi.create(form)
    },
    doUpdate: (id, form) => {
      form.prices = prices.value
        .filter((p) => p.visible && p.price != null)
        .map((item) => {
          return {
            sizeId: item.sizeId,
            price: item.price,
          }
        })
      return processApi.update(id, form)
    },
    doDelete: processApi.delete,
    doGet: (id) => {
      return new Promise((resolve) => {
        initPrices(false)
        processApi.get(id).then(({ data }) => {
          data.prices.forEach((item) => {
            const p = prices.value.find((p) => p.sizeId == item.sizeId)
            p.visible = true
            p.price = item.price
          })

          resolve({ data: data })
        })
      })
    },
    refresh: () => tableRef.value?.handleSearch(),
  })

const getSize = (id: string) => {
  return sizes.value.find((s) => s.id == id)
}

const onCheckAll = () => {
  prices.value.forEach((p) => (p.visible = true))
}
const onUnCheck = () => {
  prices.value.forEach((p) => (p.visible = !p.visible))
}

const onAdd = () => {
  initPrices()
  handleAdd()
}

const initPrices = (v = true) => {
  prices.value.forEach((item) => {
    item.visible = v
    item.price = null
  })
}

onMounted(() => {
  sizeApi.all().then(({ data }) => {
    sizes.value = data

    prices.value = data.map((item) => {
      return {
        visible: true,
        price: null,
        sizeId: item.id,
      }
    })
  })

  tableRef.value?.handleSearch()
})
</script>

<style scoped></style>
